package com.ykt.common.thirdapi.ys7;

import com.alibaba.fastjson.TypeReference;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.ykt.common.thirdapi.ys7.model.Ys7Camera;
import com.ykt.common.thirdapi.ys7.model.Ys7UserToken;
import com.ykt.common.thirdapi.ys7.model.Ys7Vo;
import com.ykt.common.utils.HTTPClientUtil;
import com.ykt.common.utils.JsonConverter;
import com.ykt.common.utils.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 萤石云api帮助类
 * @author long.hua
 * @version 1.0.0
 * @since 2016-01-11 21:20
 */
public class Ys7ApiHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(Ys7ApiHelper.class);

    private Prop prop = PropKit.use("ys7.properties");
    private String url = prop.get("ys7.url");
    private String timeUrl = prop.get("ys7.time.url"); // 获取服务器时间请求地址
    private String appKey = prop.get("ys7.app.key");
    private String secret = prop.get("ys7.secret");
    private String phone = prop.get("ys7.phone");


    public String getAccessToken(){
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("phone", phone);

        Map<String, Object> map = paramsInit("token/getAccessToken", paramsMap);
        String result = HTTPClientUtil.sendPostRequest(url, JsonKit.toJson(map));

        try {
            Ys7Vo<Ys7UserToken> vo = JsonConverter.parse(result, new TypeReference<Ys7Vo<Ys7UserToken>>() {
            });
            return vo.getResult().getData().getAccessToken();
        } catch (Exception e) {
            LOGGER.info("请求Token失败，返回信息：{}", result, e);
        }
        return null;
    }

    private Map<String, Object> paramsInit(String method, Map<String, Object> paramsMap) {
        long time = System.currentTimeMillis() / 1000;

        List<String> paramList = new ArrayList<>();
        for (String k : paramsMap.keySet()) {
            String param = k + ":" + paramsMap.get(k);
            paramList.add(param);
        }

        StringBuilder paramString = new StringBuilder();

        String[] params = paramList.toArray(new String[paramList.size()]);
        Arrays.sort(params);
        for (String param : params) {
            paramString.append(param).append(",");
        }
        paramString.append("method").append(":").append(method).append(",");
        paramString.append("time").append(":").append(time).append(",");
        paramString.append("secret").append(":").append(secret);

        String sign = null;
        try {
            sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("MD5字节数转换为小写16进制数异常！", e);
        }

        Map<String, Object> systemMap = new LinkedHashMap<>();
        systemMap.put("ver", "1.0");
        systemMap.put("sign", sign);
        systemMap.put("key", appKey);
        systemMap.put("time", time);

        Map<String, Object> requestMap = new LinkedHashMap<>();
        requestMap.put("system", systemMap);
        requestMap.put("method", method);
        requestMap.put("params", paramsMap);
        requestMap.put("id", "YKT"+time);

        return requestMap;
    }


    // 获取YS7服务器时间
    public long getServerTime() {
        Map<String, Object> header=new HashMap<>();
        header.put("appKey", appKey);
        String result =  HTTPClientUtil.sendPostRequest(timeUrl, header);

        try {
            Ys7Vo<Map<String, Long>> vo = JsonConverter.parse(result, new TypeReference<Ys7Vo<Map<String, Long>>>(){});
            return vo.getResult().getData().get("serverTime");
        } catch (Exception e) {
            LOGGER.error("获取萤石云服务器时间异常，返回信息：{}", result, e);
        }
        return -1;
    }

    // 字符串判断比json转换高效
    private boolean isOk(String responseString){
        if(responseString == null || responseString.isEmpty()){
            return false;
        }
        responseString = StringUtil.trimAll(responseString, ' ');

        return responseString.indexOf("\"code\":\"200\"") > 0;
    }

    /**
     * 循环获取设备列表，保存到数据库
     */
    public List<Ys7Camera> getCameraList(int offset, int pageSize, String token){
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("accessToken", token);
        paramsMap.put("pageStart", offset);
        paramsMap.put("pageSize", pageSize);

        Map<String, Object> map = this.paramsInit("cameraList", paramsMap);
        String json = HTTPClientUtil.sendPostRequest(url, JsonKit.toJson(map));
        if(isOk(json)){
            Ys7Vo<List<Ys7Camera>> vo = JsonConverter.parse(json, new TypeReference<Ys7Vo<List<Ys7Camera>>>(){});
            return vo.getResult().getData();
        }else {
            LOGGER.info("Requst YS7 sms error, response: {}", json);
            return null;
        }
    }

}